package service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.wemedia.WemediaContans;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vo.WmNewsVo;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import mapper.WmMaterialMapper;
import mapper.WmNewsMapper;
import mapper.WmNewsMaterialMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import service.WmNewsService;

import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Resource
    private WmMaterialMapper wmMaterialMapper;
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Resource
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findPage(WmNewsPageReqDto dto) {
        //检查参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页参数
        dto.checkParam();
        //判断用户的登录的状态
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
        //判断查询的条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //状态
        queryWrapper.eq(dto.getStatus()!=null, WmNews::getStatus,dto.getStatus());
        //关键字
        queryWrapper.like(dto.getKeyword()!=null, WmNews::getTitle,dto.getKeyword());
        //频道
        queryWrapper.eq(dto.getChannelId()!=null, WmNews::getChannelId,dto.getChannelId());
        //时间
        queryWrapper.between(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null, WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        //开始分页
        Page pageInfo = new Page(dto.getPage(),dto.getSize());
        IPage page = page(pageInfo, queryWrapper);
        //结果封装
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto, Integer status) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存新闻
        //2.1查询用户的id
        Integer uid = WmThreadLocalUtils.getUser().getApUserId();
        if(uid==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
        //2.2保存新闻
        WmNews wmNews = saveContent(dto, uid,status);
        //3.获取图片中的URL
        List<String> imageUrl = getContentImageUrl(dto);
        //4.保存内容图片和素材之间的关系
        saveContentImageMaterial(imageUrl,wmNews, WemediaContans.WM_CONTENT_REFERENCE);
        //5.保存封面与新闻的关联
        saveInFoImage(imageUrl,wmNews,dto);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findByIdNews(Integer id) {
        //判断id是否为空
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //进行查询
        WmNews wmNews = getById(id);
        ResponseResult result = ResponseResult.okResult(wmNews);
        return result;
    }

    @Override
    public ResponseResult updateStatusAndReason(WmNews wmNews) {
        LambdaUpdateWrapper<WmNews> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(WmNews::getStatus,wmNews.getStatus());
        lambdaUpdateWrapper.set(WmNews::getReason,wmNews.getReason());
        lambdaUpdateWrapper.eq(WmNews::getId,wmNews.getId());
        update(lambdaUpdateWrapper);
        return ResponseResult.okResult("ok");
    }



    //保存封面图片和文章之间的关联
    public ResponseResult saveInFoImage(List<String> imageUrl, WmNews wmNews, WmNewsDto dto){
        //判断封面是否为自动
        if(dto.getType()== WemediaContans.WM_NEWS_TYPE_AUTO){
            //获取内容中的图片数量
            int picNum = imageUrl.size();
            if(picNum>2){
                //三张图
                wmNews.setType(WemediaContans.WM_NEWS_CONENT_NONE_IMAGE);
                //取三张图
                imageUrl = imageUrl.stream().limit(3).collect(Collectors.toList());
            }else if(picNum<=2&&picNum>0){
                //一张图
                wmNews.setType(WemediaContans.WM_NEWS_CONENT_SINGLE_IMAGE);
                imageUrl = imageUrl.stream().limit(1).collect(Collectors.toList());
            }else{
                //说明无图
                wmNews.setType(WemediaContans.WM_NEWS_CONENT_MANY_IMAGE);
            }
        }
        //修改wm_news_meterial表中的images字段wmNews字段
        LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmNews::getType,wmNews.getType());
        updateWrapper.set(WmNews::getImages, imageUrl.toString().replace("[","").replace("]","").replace(" ","").trim());
        updateWrapper.eq(WmNews::getId,wmNews.getId());
        update(updateWrapper);
        //根据封面图片的URL找出对应的id
        List<Integer> ids = findByURL(imageUrl, wmNews);
        wmNewsMaterialMapper.insertContentMaterial(ids,wmNews.getId(), WemediaContans.WM_COVER_REFERENCE);
        return null;
    }
    //保存新闻
    public WmNews saveContent(WmNewsDto dto, Integer uid, Integer status){
        //添加和修改走的同一套方法，唯一区别添加没有id，修改有id
        //2.2WmNewsDto中的数据保存在WmNews对象中
        WmNews wmNews = dto2WmNews(dto);
        boolean flag;
        if(wmNews.getId()==null){
            //说明是添加
            //wmNews.setStatus(status);
            wmNews.setUserId(uid);
            //保存WmNews
            //save(wmNews);
            //从dto中获取对应的图片保存在wm_news表中
            //2.3将封面图片获取出来保存在wmUser中
            String imagesStr = dto.getImages().toString();
            //判定imagesStr为空
            if(imagesStr!=null&&imagesStr.length()>0){
                //imagesStr不为空说明封面图片不是无图或者自动
                String newImages = imagesStr.replace("[", "").replace("]", "").replace(" ", "");
                wmNews.setImages(newImages);
            }
            //保存WmNews
            flag=save(wmNews);
        }else {
            //说明是修改
            //为了避免关联重复添加，需要先将关联信息删除
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId());
            //先删除关系
            wmNewsMaterialMapper.delete(queryWrapper);
            //进行更新
            flag=updateById(wmNews);
        }
        //消息的发送
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC,JSON.toJSONString(wmNews.getId()));

        return wmNews;
    }
    //获取内容中的图片的URL
    public List<String> getContentImageUrl(WmNewsDto dto){
        //获取内容的图片的URL
        String content = dto.getContent();
        //将新闻内容通过fastjson解析成map形式
        List<Map> maps = JSON.parseArray(content, Map.class);
        //新建一个集合保存图片的URL
        List<String> imageUrl = new ArrayList<>();
        for (Map<String,String> map : maps) {
            if(map.get("type").equals(WemediaContans.WM_NEWS_TYPE_IMAGE)){
                String url = map.get("value");
                if(url!=null){
                    imageUrl.add(url);
                }
            }
        }
        return imageUrl;
    }
    //根据URL获取对应的图片id
    public List<Integer> findByURL(List<String> imageUrl, WmNews wmNews){
//根据图片的URL去查询图片的id
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //设置URL的条件
        queryWrapper.in(WmMaterial::getUrl,imageUrl);
        //设置用户id
        queryWrapper.eq(WmMaterial::getUserId,wmNews.getUserId());
        //获取对应图片的数据
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        //键值对  id，url
        Map<String, Integer> collect = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        //声明list对应的图片数据
        List<Integer> ids = new ArrayList<>();
        //遍历
        for (String url :imageUrl) {
            Integer id = collect.get(url);
//            if(id==null){
//                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"无效图片");
//            }
            //保存图片的id
            ids.add(id);
        }
        return ids;
    }
    //保存内容图片和素材之间的关系
    public ResponseResult saveContentImageMaterial(List<String> imageUrl, WmNews wmNews, Integer type){
        List<Integer> ids = findByURL(imageUrl, wmNews);
        //获取新闻的id
        Integer newsId = wmNews.getId();
        //执行保存
        wmNewsMaterialMapper.insertContentMaterial(ids,newsId, WemediaContans.WM_CONTENT_REFERENCE);

        return null;
    }

    //WmNewsDto中的数据保存在WmNews对象中
    public WmNews dto2WmNews(WmNewsDto dto){
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        wmNews.setChannelId(dto.getChannelId());
        wmNews.setContent(dto.getContent());
        wmNews.setCreatedTime(new Date());
        wmNews.setLabels(dto.getLabels());
        wmNews.setTitle(dto.getTitle());
        wmNews.setStatus(dto.getStatus());
        wmNews.setSubmitedTime(new Date());
        wmNews.setPublishTime(dto.getPublishTime());
        wmNews.setType(1);
        //将dto当中和我们，News相同的属性进行赋值
        //BeanUtils.copyProperties(dto,wmNews);
        return wmNews;
    }

    @Override
    public List<Integer> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime, new Date()));
        List<Integer> listIds = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return listIds;
    }

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer currentPages =  (dto.getPage()-1)+ dto.getSize();
        List<WmNewsVo> list = wmNewsMapper.findList(dto.getTitle(), currentPages, dto.getPage());
        Integer count = wmNewsMapper.selectCount(null);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        responseResult.setData(list);
        return responseResult;
    }
}
